package com.cy.task;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class DynamicScheduleTask implements SchedulingConfigurer {

    private static final Logger LOGGER = LoggerFactory.getLogger(DynamicScheduleTask.class);


    @Mapper
    public interface CronMapper {
        @Select("select cron from cron")
        public List<String> getCron();

        @Select("select type from cron")
        public List<Integer> getType();
    }

    @Autowired
    @SuppressWarnings("all")
    CronMapper cronMapper;

    private Map<String, ScheduledFuture<?>> futures;

    /**
     * 执行定时任务.
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        try {
            cronMapper.getCron().forEach((cron)->{
                taskRegistrar.addTriggerTask(
                        //1.添加任务内容(Runnable)，可以为方法
                        () -> System.out.println("定时任务1"),
                        //2.设置执行周期(Trigger)
                        triggerContext -> {
                            //2.1 从数据库获取执行周期，在这里调用不同的方法返回不同的定时任务信息
                            System.out.println(cron);
                            //2.2 合法性校验.
                            if (StringUtils.isEmpty(cron)) {
                                // Omitted Code ..
                                LOGGER.error("计划任务为空");
                            }
                            //2.3 返回执行周期(Date)
                            return new CronTrigger(cron).nextExecutionTime(triggerContext);
                        }
                );
            });
        } catch (Exception e) {
            LOGGER.info(e.getMessage());
        }
    }
}